package com.EWS.controller;

import com.EWS.model.UserDto;
import com.EWS.service.UserService;
import com.EWS.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

// 与前端交互进行注册和登录
// servlet 配置有两种方式：1.在web.xml配置 2.使用注解
@WebServlet("/userRegisterServlet")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    // 转换注册页面提交的信息
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 接收前端页面提交的信息
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        // 将前端注册提交的信息转换为javabean
        UserDto userDto = new UserDto();
        userDto.setUserName(userName);
        userDto.setPassWord(passWord);
        // 将信息传到Service层加密，再传到Dao层与数据库进行交互
        int result = userService.register(userDto);
        if(result > 0){
            System.out.println("添加成功！");
            // 注册成功跳转到登录界面
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else{
            System.out.println("添加失败！");
        }
    }

    // 转换登录界面的信息
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 将获取到的用户信息传到Service层，Service将通过Dao层与数据库交互获取的信息与输入的信息进行比较判断，这里返回比较结果
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        String result = userService.login(userName,passWord);
        // 根据用户信息的判断结果跳转页面
        // 用户不存在，跳转注册界面
        if("NoExist".equals(result)) {
            req.getRequestDispatcher("register.jsp").forward(req,resp);
        }
        // 登录成功，跳转到用户数据显示界面
        if("loginSuccess".equals(result)){
            // 将用户名这个值传到前端system.jsp中
            HttpSession session = req.getSession();
            session.setAttribute("userName",userName);
            req.getRequestDispatcher("system.jsp").forward(req,resp);
        }
        // 登录失败，密码出错，刷新登录界面重新输入密码
        if("loginFail".equals(result)){
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
